package com.bzchao.consumer;

import com.rabbitmq.client.Channel;
import com.bzchao.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class OrderReceiver {
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "order-queue", declare = "true"),
            exchange = @Exchange(value = "order-exchange", declare = "true", type = "topic"),
            key = "order.*"
    ))
    @RabbitHandler
    public void onOrderMsg(@Payload Order order, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        log.info("收到消息：{},{}", order, headers);
        if (order.getId() - 11 == 0) {
            throw new RuntimeException("错误,请重试");
        }
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //手动确认消息被消费
        channel.basicAck(deliveryTag, true);
        log.info("消费成功，deliveryTag{}", deliveryTag);
    }
}
